<template>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>

  </el-row>
  <div>
    <el-card><div ref="chart" style="height: 300px; width: 1300px"></div></el-card>
    <el-card><div ref="chart2" style="height: 300px; width: 1300px"></div></el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { useRouter } from "vue-router";
// import Index from "./views/index/index.vue";



const value2 = ref([]);

const shortcuts = [
  {
    text: "近1周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "近2周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 14);
      return [start, end];
    },
  },
  {
    text: "近1月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); 
const chart2 = ref();
const chartInstance2 = ref(null);
const series_data2 = ref();
const series_data = ref();
const series_data1 = ref();

const initChart = async () => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  let option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        // params 是一个数组，包含了所有在当前横坐标上的系列数据
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["空位","满位"],
      orient: "horizontal", // 改为水平显示
      left: "left", // 将图例放置在左侧
      top: "top", // 将图例放置在顶部
      itemGap: 10, // 图例项之间的间距
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },

    title: {
      text: `${value3.value} 空满位整线统计`,
      left: "center",
      subtext: "分钟",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data1.value,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "空位",
        data: series_data.value,
        type: "bar",
        stack:'total',
        color: "#59c4e6",
      },
      {
        name: "满位",
        data: series_data2.value,
        type: "bar",
        stack:'total',
        color: "#edafda",
      },
    ],
  };
  myChart.on('click', (params) => {
    console.log('Clicked:', params);
    const equipment_id = params.name;
    useShowDataInHtmlForTable(equipment_id);
  });
  myChart.setOption(option);
};

const initChart2 = async (equipmentId) => {
  if (chartInstance2.value == null) {
    return;
  }

  echarts.dispose(chartInstance2.value);
  var myChart2 = echarts.init(chartInstance2.value);
  myChart2.setOption({});

  let option2 = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["空位", "满位"],
      orient: "horizontal", 
      left: "left", 
      top: "top", 
      itemGap: 10, 
    },
    title: {
      text: `OP${equipmentId} 空满位情况`,
      subtext: "m/小时",
      left: "center",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data3.value,
    },
    dataZoom: [
      {
        type: "slider", 
        start: 0, 
        end: 100, 
      },
      {
        type: "inside", 
        start: 90, 
        end: 100, 
      },
    ],
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "空位",
        data: series_data4.value,
        type: "bar",
        color: "#5470c6",
        stack: 'toatl'
      },
      {
        name: "满位",
        data: series_data5.value,
        type: "bar",
        color: "#edafda",
        stack: 'toatl'
      },
    ],
  };
  myChart2.setOption(option2);
};

onMounted(() => {
  const todayStart = new Date();
  todayStart.setHours(7, 0, 0, 0); 
  const todayEnd = new Date(); 
  value2.value = [todayStart, todayEnd];
  use_show_data_in_html2();
  chartInstance2.value = chart2.value; 
  initChart2();
});

const value3 = ref("装配A");
const router = useRouter();
const options = [
  { value: "装配A", label: "装配A" },
  { value: "装配B", label: "装配B" },
  { value: "缸体M1", label: "缸体M1" },
  { value: "缸体M2", label: "缸体M2" },
  { value: "缸盖M1", label: "缸盖M1" },
  { value: "缸盖M2", label: "缸盖M2" },
  { value: "曲轴M1", label: "曲轴M1" },
];
const excludedpoint = ["1006", "1008","1035","1075","1115","1140","1150","1165","1196","1235","1245","1315","1368"]
function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

var construct_url = "";
watch([toRef(value2), toRef(value3)], ([newDateRange, newValue3]) => {
  const start_time = formatDate(newDateRange[0]);
  const end_time = formatDate(newDateRange[1]);
  construct_url = "http://10.64.35.32:8000/man_ana_sql_server/get_station_status/?" + "start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&sub_area=" + newValue3 +"&page_size=" + 100001;
  use_show_data_in_html2();
});

const series_data3 = ref();
const series_data4 = ref();
const series_data5 = ref();


const use_show_data_in_html2 = async () => {
  console.log(construct_url);
  const response = await axios.get(construct_url);
  const data = response.data.filter(item => !excludedpoint.includes(item.equipment_id));
  console.log(data);
  series_data1.value = [];
  series_data.value = [];
  series_data2.value = [];

  const timeSumByEquipment = new Map();

  data.forEach(item => {
    const equipmentId = item.equipment_id;
    const callType = item.call_type;
    const duringTime = item.during_time;

    if (!timeSumByEquipment.has(equipmentId)) {
      timeSumByEquipment.set(equipmentId, { empty: 0, full: 0 });
    }

    if (callType === "空位") {
      timeSumByEquipment.get(equipmentId).empty += duringTime;
    } else if (callType === "满位") {
      timeSumByEquipment.get(equipmentId).full += duringTime;
    }
  });
  const sortedKeys = Array.from(timeSumByEquipment.keys()).sort((a, b) => a.substring(0, 3).localeCompare(b.substring(0, 3)));
  series_data1.value = sortedKeys;
  series_data.value = sortedKeys.map(key => parseFloat((timeSumByEquipment.get(key).empty / 60).toFixed(2)));
  series_data2.value = sortedKeys.map(key => parseFloat((timeSumByEquipment.get(key).full / 60).toFixed(2)));
  console.log(series_data2.value)
  initChart();
};

  const generateTimeIntervals = (startTime, endTime, intervalUnit = 'hour') => {
    const intervals = [];
    let currentDate = new Date(startTime);
    const endDate = new Date(endTime);

    while (currentDate <= endDate) {
        const formattedDate = formatDate(currentDate); // 使用完整的日期时间格式
        intervals.push(extractHourFromTimestamp(formattedDate));
        currentDate.setHours(currentDate.getHours() + 1); // 每小时增加一小时
    }

    return intervals;
};

const extractHourFromTimestamp = (timestamp) => {
    if (timestamp) {
        const date = new Date(timestamp);
        const year = date.getFullYear().toString().substring(2); 
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); 
        const day = date.getDate().toString().padStart(2, '0'); 
        const hour = date.getHours().toString().padStart(2, '0'); 
        const nextHour = (hour === "23") ? "00" : (parseInt(hour) + 1).toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:00-${nextHour}:00`;
    }
    return null;
};

const useShowDataInHtmlForTable = async (equipmentId) => {
    try {
        const start_time = formatDate(value2.value[0]);
        const end_time = formatDate(value2.value[1]);

        const url = `http://10.64.35.32:8000/man_ana_sql_server/get_station_status/?start_time=${start_time}&end_time=${end_time}&sub_area=${value3.value}&equipment_id=${equipmentId}&page_size=100001`;
        console.log(url);
        const response = await axios.get(url);
        const data = response.data.filter(item => !excludedpoint.includes(item.equipment_id));
        console.log(data);

        const timeSumByHour = new Map();

        data.forEach(item => {
            const callType = item.call_type;
            const duringTime = item.during_time;
            const hourKey = extractHourFromTimestamp(item.start_time); 

            if (hourKey !== null) { 
                if (!timeSumByHour.has(hourKey)) {
                    timeSumByHour.set(hourKey, { empty: 0, full: 0 });
                }

                if (callType === '空位') {
                    timeSumByHour.get(hourKey).empty += duringTime;
                } else if (callType === '满位') {
                    timeSumByHour.get(hourKey).full += duringTime;
                }
            }
        });

        const timeIntervals = generateTimeIntervals(start_time, end_time, 'hour'); 
        series_data3.value = timeIntervals; 
        series_data4.value = timeIntervals.map(hour => ((timeSumByHour.get(hour)?.empty || 0) / 60).toFixed(2)); 
        series_data5.value = timeIntervals.map(hour => ((timeSumByHour.get(hour)?.full || 0) / 60).toFixed(2));
        initChart2(equipmentId);
    } catch (error) {
        console.error(error);
        ElMessage.error('加载数据失败。');
    }
};
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important;
  overflow-y: auto !important;
}
</style>
